const express = require('express');
const si = require('systeminformation');
const app = express();
const port = 3000;

app.use(express.static('public'));

app.get('/api/hardware', async (req, res) => {
  try {
    const [cpu, mem, graphics, fsSize] = await Promise.all([
      si.cpu(),
      si.mem(),
      si.graphics(),
      si.fsSize()
    ]);

    const totalStorage = fsSize.reduce((acc, disk) => acc + disk.size, 0);
    const freeStorage = fsSize.reduce((acc, disk) => acc + disk.available, 0);

    res.json({
      cpu: {
        name: cpu.manufacturer + ' ' + cpu.brand,
        cores: cpu.cores,
        threads: cpu.physicalCores
      },
      memory: {
        total: (mem.total / 1024 ** 3).toFixed(1),
        available: (mem.available / 1024 ** 3).toFixed(1)
      },
      gpu: graphics.controllers.map(gpu => ({
        name: gpu.model,
        vram: (gpu.vram / 1024).toFixed(1)
      })),
      storage: {
        total: (totalStorage / 1024 ** 3).toFixed(1),
        free: (freeStorage / 1024 ** 3).toFixed(1)
      }
    });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.get('/api/network-test', (req, res) => {
  const interfaces = require('os').networkInterfaces();
  const addresses = [];
  Object.keys(interfaces).forEach(ifname => {
    interfaces[ifname].forEach(iface => {
      if ('IPv4' === iface.family && iface.internal === false && iface.address !== '127.0.0.1' 
        && iface.address.startsWith('169.254.') === false && iface.address !== '::1' 
        && iface.mac !== '00:00:00:00:00:00') {
        addresses.push({
          address: iface.address,
          netmask: iface.netmask,
          interface: ifname,
          status: iface.operstate === 'up' ? '已连接' : '未连接'
        });
      }
    });
  });
  res.json({
    success: addresses.length > 0,
    localIPs: addresses,
    message: addresses.length === 0 
      ? '未检测到有效IPv4地址，请检查：1.网络连接 2.防火墙设置 3.虚拟网卡配置' 
      : '检测到' + addresses.length + '个有效网络接口'
  });
});

app.listen(port, '0.0.0.0', () => {
  console.log(`Server running at http://localhost:${port}`);
});